import React, { useState } from 'react'
import { faPlus, faFileImport, faSave } from '@fortawesome/free-solid-svg-icons'
import SimpleMDE from "react-simplemde-editor"
import uuidv4 from 'uuid/v4'
import { flattenArr,objToArr } from './utils/helper'
// import fileHelper from './utils/fileHelper'
import './App.css'
import 'bootstrap/dist/css/bootstrap.min.css'
import "easymde/dist/easymde.min.css"

import FileSearch from './components/FileSearch'
import FileList from './components/FileList'
import BottomBtn from './components/BottomBtn'
import TabList from './components/TabList'
import defaultFiles from './utils/defaultFiles'

//require node.js modules
// const { join } = require('path');
// const { remote } = require('electron');
// const { join } = window.require('path');
// const { remote } = window.require('electron');

function App() {
  const [ files, setFiles ] = useState(flattenArr(defaultFiles))
  console.log(files)
  const [ activeFileID, setActiveFileID ] = useState('')
  const [ openedFileIDs, setOpenedFileIDs ] = useState([])
  const [ unsavedFileIDs, setUnsavedFileIDs ] = useState([])
  const [ searchedFiles, setSearchedFiles ] = useState([])
  const filesArr = objToArr(files)
  // const savedLocation = remote.app.getPath('documents')
  const activeFile = files[activeFileID]
  const openedFiles = openedFileIDs.map(openID =>{
    return files[openID]
  })
  const fileListArr = (searchedFiles.length > 0) ? searchedFiles : filesArr

  const fileClick = (fileID) =>{
    // 设置当前的id
    setActiveFileID(fileID)
    //openedFiles没有当前的id 没有再加
    // add new fileID to openedFiles 放到右边，加到setOpenedFileIDs
    if(!openedFileIDs.includes(fileID)){
      setOpenedFileIDs([...openedFileIDs, fileID])
    }
  }

  const tabClick = (fileID) =>{
    // 设置当前的id
    setActiveFileID(fileID)
  }

  const tabClose = (id) =>{
    //移除当前id
    const tabsWithout = openedFileIDs.filter(fileID => fileID !== id)
    setOpenedFileIDs(tabsWithout)
    //如果还有打开的标签，则将活动标签设置为第一个打开的标签
    if(tabsWithout.length > 0){
      setActiveFileID(tabsWithout[0])
    } else {
      setActiveFileID('')
    }
  }

  const fileChange = (id, value) =>{
    const newFile = { ...files[id],body:value }
    setFiles({...files, [id]:newFile })
    //更新未保存的ID
    if(!unsavedFileIDs.includes(id)){
      setUnsavedFileIDs([...unsavedFileIDs, id])
    }
  }
  //删除
  const deleteFile = (id) =>{
    //过滤掉当前文件ID
    delete files[id]
    setFiles(files)
    //如果打开，请关闭标签页
    tabClose(id)
  }
  //修改
  // const updateFileName = (id, title, isNew) =>{
  //   const modifiedFile = { ...files[id],title,isNew:false }
  //   if(isNew){
  //     fileHelper.writeFile(join(savedLocation, `${title}.md`),files[id].body).then(() =>{
  //       setFiles({...files, [id]:modifiedFile})
  //     })
  //   } else {
  //     fileHelper.renameFile(join(savedLocation, `${files[id].title}.md`),
  //       join(savedLocation, `${title}.md`)
  //     ).then(() =>{
  //       setFiles({...files, [id]:modifiedFile})
  //     })
  //   }
   
  // }
  //搜索
  const fileSearch = (keyword) =>{
    //根据关键词筛选新文件
    const newFiles = filesArr.filter(file => file.title.includes(keyword))
    setSearchedFiles(newFiles)
  }
  //新建
  const createNewFile = () =>{
    const newID = uuidv4()
    const newFile = {
        id:newID,
        title:'',
        body:'## 请输出 Markdown',
        createdAt: new Date().getTime(),
        isNew:true,
    }
    setFiles({ ...files, [newID]:newFile})
  }
  /* const saveCurrentFile = () =>{
    fileHelper.writeFile(join(savedLocation,`${activeFile.title}.md`),
      activeFile.body
    ).then(() => {
      setUnsavedFileIDs(unsavedFileIDs.filter(id => id !== activeFile.id))
    })
  } */

  return (
    <div className="App container-fluid px-0">
      <div className='row no-gutters'>
        <div className='col-3 left-panel'>
          <FileSearch 
             title='My Document'
             onFileSearch={fileSearch}
          />
          <FileList 
            files={fileListArr}
            onFileClick={fileClick}
            onFileDelete={deleteFile}
          />
          <div className='row no-gutters button-group'>
            <div className='col'>
              <BottomBtn 
                text="新建"
                colorClass="btn-primary"
                icon={faPlus}
                onBtnClick={createNewFile}
              />
            </div>
            <div className='col'>
              <BottomBtn 
                text="导入"
                colorClass="btn-success"
                icon={faSave}
              />
            </div>
          </div>
        </div>
        <div className='col-9 right-panel'>
          { !activeFile && 
            <div className='start-page'>
              选择或者创建新的 Markdown 文档
            </div>
          }
          { activeFile && 
            <>
              <TabList
                files={openedFiles}
                activeId={activeFileID}
                unsaveIds={unsavedFileIDs}
                onTabClick={tabClick}
                onCloseTab={tabClose}
              />
              <SimpleMDE
                key={activeFile && activeFile.id}
                value={activeFile && activeFile.body}
                onChange={(value) => {fileChange(activeFile.id,value)}}
                options={{
                  minHeight: '515px',
                }}
              />
            </>
          }
        </div>
      </div>
    </div>
  );
}

export default App;
